package com.farmlei.zkt_c3100.lock;

import com.farmlei.zkt_c3100.common.PropertiesUtils;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.Date;

/**
 * 中控门禁控制器操作工具类
 */
public class ZktecoUtil {
    private static final Logger logger = LoggerFactory.getLogger(ZktecoUtil.class);
    private static final int BUFFER_SIZE = 4 * 1024;//从控制器获取数据的长度
    private static final String DOOR_IP =  PropertiesUtils.getConfig().getString("doorIp", "192.168.1.201");
    private static final int DOOR_PORT =  PropertiesUtils.getConfig().getInt("doorPort", 4370);
    private static final String DOOR_PASSWORD =  PropertiesUtils.getConfig().getString("doorPassword", "");

    /**
     * 获取最新的刷卡记录，该方法返回最新的卡号
     * @return 卡号
     */
	static void getLatestRecordsAndOpenDoor() {
		Pointer pointer = null;
		try {
			String format = "protocol=TCP,ipaddress=" + DOOR_IP + ",port=" + DOOR_PORT + ",timeout=4000,passwd="
					+ DOOR_PASSWORD;
			IntByReference code = new IntByReference();
			pointer = PullLibrary.Instance.ConnectExt(format, code);
			// 连接成功
			if (pointer != null && code.getValue() == 0) {
				byte[] buffer = new byte[BUFFER_SIZE];
				//EventType=27 表示此卡号在门禁控制器里不存在，需要调后台接口判断身份权限
				PullLibrary.Instance.GetDeviceData(pointer, buffer, new IntByReference(1024), "transaction",
						"Cardno\tInOutState\tDoorID", "EventType=27", "NewRecord");

				// 清除空数据
				int length = 0;
				for (int i = 0; i < buffer.length; ++i) {
					if (buffer[i] == 0) {
						length = i;
						break;
					}
				}

				if (length > 0) {
					String records = new String(buffer, 0, length);
					String[] recordLines = records.split("\r\n");
					if (recordLines.length > 1) {
						String lastRecord = recordLines[recordLines.length - 1];
                        //如果一次取到多条记录，只判断最新的一条刷卡数据
						if (StringUtils.isNotBlank(lastRecord)) {
							if (StringUtils.isNotBlank(lastRecord)) {
								String[] recordArr = lastRecord.split(",");
								if (recordArr.length > 2) {
									// 获取卡号
									String cardNum = recordArr[0];
                                    boolean canOpen = false;
									//TODO 写上自己的业务代码，判断卡号是否存在，是否有权限开此门等等
									if (canOpen) {
									    //调用门禁控制器开锁接口
                                        PullLibrary.Instance.ControlDevice(pointer,
                                                new NativeLong(Long.parseLong(recordArr[2])),
                                                new NativeLong(1), new NativeLong(1), new NativeLong(3),
                                                new NativeLong(0), "");
                                    }

								}
							}
						}
					}
				}
			} else {
                logger.error("连接门禁控制器失败");
            }
		} catch (Exception e) {
			logger.error("读取刷卡记录出现异常，异常信息：{}", e.getMessage());
		} catch (Error e) {
			logger.error("读取刷卡记录出现错误，错误信息：{}", e.getMessage());
		} finally {
			// 最后关闭连接
			try {
				if (pointer != null) {
					PullLibrary.Instance.Disconnect(pointer);
				}
			} catch (Exception e) {
			}
		}
	}

    /**
     * 时间戳转换成日期类型
     * @param time 时间戳
     * @return 日期
     */
    private static Date convertTime(long time) {
        long second = time % 60;//秒
        time /= 60;
        long minute = time % 60;//分钟
        time /= 60;
        long hour = time % 24;
        time /= 24;
        long day = time % 31 + 1;
        time /= 31;
        long month = time % 12 + 1;
        time /= 12;
        long year = time + 2000;

        String dateStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

        try {
            return DateUtils.parseDate(dateStr, new String[]{"yyyy-M-d h:m:s"});
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        long time = 596371060;
        System.out.println(convertTime(596371760));

    }
}
